/**
 * Created by sj on 15/4/14.
 */
(function () {
  'use strict';
  angular.module('sasApp.directives')
    /*
     *  表单验证（开始结束时间比对）
     *  endTime 加在开始时间的input上，
     *  startTime 加在结束时间的input上
     **/
    .directive('selfForm', selfForm);
  function selfForm(userRequest,$cookies) {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        selfForm: '@'
      },
      link: postLink
    };
    function postLink(scope, ele, attr, ctrl) {
      ctrl.$setValidity('check-repeat', true);
      //当改变ngModel的值时，应做出判断并给予样式警告
      ctrl.$parsers.unshift(function(viewValue){
        getResult(viewValue);
        return viewValue;
      });
      var checkValue;
      function getResult(value){
        var boo = scope.selfForm;
        if(boo === 'checkName'){
          checkValue = { userName: value };
          userRequest.checkName(checkValue, checkName);
        }else if(boo === 'checkIdCard'){
          checkValue = { idCard: value };
          if(($cookies.getObject('userMngInfo') && $cookies.getObject('userMngInfo').idCard !== value )|| $cookies.getObject('userMngInfo') === undefined){
            value.length > 14 &&  userRequest.checkIdCard(checkValue, checkName);
          }
        }
      }
      function checkName(res){
        if(res.state==='10000'){
          ctrl.$setValidity('check-repeat', true);
        }else if(res.state==='10002'){ 
          ctrl.$setValidity('check-repeat', false);
        }
      }
    }
  }

})();